package tv247

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"net/http"
	"uni-crawl-frame/core"
	"uni-crawl-frame/service/crawl/videoservice"
	"uni-crawl-frame/utils/ffmpegutil"
	"uni-crawl-frame/utils/fileutil"
)

const (
	tv247Us = "https://tv247.us"
)

type TV247Crawl struct {
	*core.AbstractCrawlLiveFlow
}

func (r *TV247Crawl) LoadLiveStream(ctx *core.ApplicationContext) {

	log := g.Log().Line()
	builder := fileutil.CreateBuilder().Url(ctx.CrawlLiveCtx.LiveUrl)

	headers := http.Header{}
	headers.Set("referer", tv247Us)
	headers.Set("origin", tv247Us)

	builder = builder.Headers(headers)

	saveFile := videoservice.GetLiveM3U8CacheFile(ctx.CrawlLiveCtx.ProgramName)
	builder.SaveFile(saveFile)

	err := fileutil.DownloadFileByBuilder(builder)
	if err != nil {
		log.Error(gctx.GetInitCtx(), err)
		ctx.CrawlLiveCtx.LoadNextTimeDefault()
		return
	}

	m3u8DO, err := r.ConvertM3U8(ctx.CrawlLiveCtx.CmsCrawlLiveConfig, saveFile)
	if err != nil {
		log.Error(gctx.GetInitCtx(), err)
		ctx.CrawlLiveCtx.LoadNextTimeDefault()
		return
	}

	// 计算下次执行时间
	ctx.CrawlLiveCtx.LoadNextTimeAfterSeconds(m3u8DO.PlaySecondTotal)

	m3u8DO.Headers = &headers
	err = ffmpegutil.DownloadToLiveStream(m3u8DO)
	if err != nil {
		log.Error(gctx.GetInitCtx(), err)
		ctx.CrawlLiveCtx.LoadNextTimeDefault()
		return
	}

}
